package com.emm.yixun.mobile.ui;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.NoticeContentAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetRemindCategoryList;
import com.emm.yixun.mobile.model.GetRemindCategoryList.RemindCategoryList;
import com.emm.yixun.mobile.model.NoticeContentModel;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.swu.pulltorefresh.PullToRefreshSwipeMenuListView;
import cn.swu.pulltorefresh.PullToRefreshSwipeMenuListView.IXListViewListener;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * <p>
 * <b>Title：</b> 公告详情
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:06:58
 */
public class RemindContentActivity extends SwipeBackActivity implements IXListViewListener {

    private static final String TAG = "RemindContentActivity";

    /**
     * 标题
     */
    TextView title_main;

    /**
     * 返回按钮
     */
    ImageView back_btn;

    private String title = "";

    private String remindCategoryId = "";

    NoticeContentAdapter adapter;

    ArrayList<NoticeContentModel> name;

    PullToRefreshSwipeMenuListView listView_notice;

    /**
     * 侧滑关闭框架
     */
    private SwipeBackLayout mSwipeBackLayout;

    @Override
    protected void onResume() {
        BaseActivity.activity = this;
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notice_content_activity);

        SetSwipeBackLayout(mSwipeBackLayout);

        BaseActivity.activity = this;
        EmmApplication.IsReloadMain = true;
        title_main = (TextView) findViewById(R.id.title_main);
        back_btn = (ImageView) findViewById(R.id.back_btn);
        listView_notice = (PullToRefreshSwipeMenuListView) findViewById(R.id.listView_notice);
        title = getIntent().getStringExtra("TITLE");
        remindCategoryId = getIntent().getStringExtra("remindCategoryId");
        title_main.setText(title);

        SetRelativiLayoutPadding(R.id.main_head_top_rela);

        initBtn();
        listView_notice.setPullRefreshEnable(true);
        listView_notice.setPullLoadEnable(true);
        listView_notice.setXListViewListener(this);
        listView_notice.setRefreshTime(EmmApplication.getData("RefreshTime_notice_remind"));

        Loading.showDialogForLoading(RemindContentActivity.this, "正在加载...", false, true, 60000);
        getRemindCategoryList(remindCategoryId, "" + pageNumber, "" + pageSize, 1);

    }

    private void initBtn() {
        back_btn.setVisibility(View.VISIBLE);
        back_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    GetRemindCategoryList getremindcategory;

    /**
     * 页码
     */
    int pageNumber = 1;

    /**
     * 页码条数
     */
    int pageSize = 10;

    boolean IsLoading = true;

    /**
     * <p>
     * <b>Title：</b> 提醒列表查询接口
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param remindCategoryId
     * @param pageNumberd
     * @param pageSized
     * @param opentype
     * @author tangxin
     * @date 2016年12月7日 下午4:39:55
     */
    private void getRemindCategoryList(String remindCategoryId, String pageNumberd, String pageSized, final int opentype) {
        EmmApplication.updateUrl("getRemindCategoryList");
        Map<String, String> map = new HashMap<String, String>();

        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("remindCategoryId", remindCategoryId);
        map.put("pageNumber", pageNumberd);
        map.put("pageSize", pageSized);

        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v(TAG, "getRemindCategoryList-->post:" + EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
                listView_notice.stopRefresh();
                String timed = EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd HH:mm");
                listView_notice.setRefreshTime(timed);
                EmmApplication.setData("RefreshTime_notice_remind", timed);
                listView_notice.stopLoadMore();
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                listView_notice.stopRefresh();
                String timed = EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd HH:mm");
                listView_notice.setRefreshTime(timed);
                EmmApplication.setData("RefreshTime_notice_remind", timed);
                listView_notice.stopLoadMore();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v("content", "content=>" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }
                GetRemindCategoryList getremind = JSONObject.parseObject(resData.toString(),
                        GetRemindCategoryList.class);
                if ("1".equals(getremind.getResult())) {
                    Log.v("获取成功", "");
                    if (getremind.getRemindCategoryList() != null) {
                        if (opentype == 1) {// 刷新
                            getremindcategory = new GetRemindCategoryList();
                            getremindcategory = getremind;
                        } else {// 加载
                            if (getremindcategory != null) {
                                getremindcategory.getRemindCategoryList().addAll(getremind.getRemindCategoryList());
                            } else {
                                getremindcategory = new GetRemindCategoryList();
                                getremindcategory.getRemindCategoryList().addAll(getremind.getRemindCategoryList());
                            }
                        }
                        if (getremindcategory.getRemindCategoryList().size() < (pageNumber * pageSize)) {// 代表没有更多
                            IsLoading = false;
                            if (opentype != 1) {
                                // EmmApplication.T("没有更多客户");
                            }
                        }
                        if (adapter == null) {
                            adapter = new NoticeContentAdapter(RemindContentActivity.this, getremindcategory
                                    .getRemindCategoryList());
                            listView_notice.setAdapter(adapter);
                        } else {
                            adapter.GetDate(getremindcategory.getRemindCategoryList());
                        }
                    } else {
                        if (pageNumber > 0 && opentype != 1)
                            pageNumber--;
                        if (opentype == 1) {
                            // EmmApplication.T("没有查询到客户");
                        } else {
                            // EmmApplication.T("没有更多客户");
                        }
                        ArrayList<RemindCategoryList> arrlist;
                        if (null != getremindcategory && null != getremindcategory.getRemindCategoryList()) {
                            arrlist = getremindcategory.getRemindCategoryList();
                        } else {
                            arrlist = new ArrayList<GetRemindCategoryList.RemindCategoryList>();
                        }

                        if (adapter == null) {
                            adapter = new NoticeContentAdapter(RemindContentActivity.this, arrlist);
                            listView_notice.setAdapter(adapter);
                        } else {
                            adapter.GetDate(arrlist);
                        }
                    }
                } else {
                    EmmApplication.T(getremind.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getremind.getErrorCode().toString() + "errorMsg:"
                            + getremind.getErrorMsg().toString());
                }
            }
        });
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        listView_notice.stopLoadMore();
        h.sendEmptyMessage(1);
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        listView_notice.stopRefresh();
        h.sendEmptyMessage(2);
    }

    /**
     * 模拟加载效果
     */
    Handler h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {// 刷新
                pageNumber = 1;
                getRemindCategoryList(remindCategoryId, "" + 1, "" + pageSize, 1);
            } else if (msg.what == 2) {// 加载
                pageNumber++;
                getRemindCategoryList(remindCategoryId, "" + pageNumber, "" + pageSize, 2);
            }
        }

        ;
    };

}
